package day05;

import java.util.Scanner;

/**
 * @author Xiao
 * @date 2021/7/5
 */
public class getIndex {
    /*
        需求：
            已知一个数组{19, 28, 37, 46, 50}，键盘录入一个数，查找该数在数组中的索引值。
     */
    public static void main(String[] args) {
        int[] arr = {19, 28, 37, 46, 50};
        System.out.println("已知数组如下：");
        printArray(arr);        //  遍历数组
        System.out.println("-----------------");

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您要查找的元素：");
        int num = sc.nextInt();
        int index = -1;             //假设要查找的数不存在，index = -1
        for (int i = 0; i < arr.length; i++) {
            if (num == arr[i]) {
                index = i;
                System.out.println("index:" + index + "");
                break;             //得到结果后结束for循环,提高运行效率
            }
        }
    }

    private static void printArray(int[] arr) {
        System.out.print("{");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length-1) {
                System.out.print(arr[i]);
            } else {
                System.out.print(arr[i] + ", ");
            }
        }
        System.out.println("}");
    }
}
